package com.example.demo.controller;

import com.example.demo.entity.Comment;
import com.example.demo.entity.User;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.CommentService;
import com.example.demo.utils.BSResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/comment")
public class CommentController {


    @Autowired
    private CommentService commentService;

    @RequestMapping("/add")
    @ResponseBody
    public BSResult submitComment(Comment comment, HttpServletRequest request) {


        //  System.out.println("comment");

        User loginUser = (User) request.getSession().getAttribute("loginUser");
        try {
            comment.setUsername(loginUser.getUsername());
            commentService.insertComment(comment);
            return BSResultUtils.success("评论上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BSResultUtils.build(500, "评论上传失败");
        }
    }

    @RequestMapping("/list")

    public String commentList(Model model){


       List<Comment> comments=commentService.selectCommentByStoreId(0);
       model.addAttribute("comments",comments);

        return "/admin/comment/list";
    }

    @ResponseBody
    @RequestMapping("/delete")
    public BSResult deleteComment(int commentId){

        try{
            commentService.deleteByCommentId(commentId);
            return BSResultUtils.build(200,"删除成功！");

        }catch(Exception e){
            e.printStackTrace();
            return BSResultUtils.build(404,"删除失败，请重新再试！");
        }
    }

    @RequestMapping("/update/{commentId}")
    public String update(@PathVariable(value = "commentId")Integer commentId,Model model){

        Comment comment=commentService.selectByCommentId(commentId);
        model.addAttribute("comment",comment);
        return "/admin/comment/edit";
    }

    @RequestMapping(value = "/echo")
    public String updateEdit(Comment comment){


            System.out.println("comment update" );
           commentService.updateComment(comment);
        return "forward:/comment/list";

    }






}
